//
//  YXDownloaderManager.m
//  MockProject
//
//  Created by FanYu on 30/8/2016.
//  Copyright © 2016 niuzhaowang. All rights reserved.
//

#import "YXDownloaderManager.h"
#import "YXBaseDownloadTool.h"
#import "YXTaskManager.h"

@interface YXDownloaderManager ()


@end


@implementation YXDownloaderManager

+ (void)getTaskSizeByURL:(NSString *)url success:(void (^)(id))success failure:(void (^)(id ))failure {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [YXBaseDownloadTool head:url params:nil success:^(NSString *sizeBytes) {
            success(sizeBytes);
        } failure:^(NSError *error) {
            failure(@"Failure");
        }];
    });
}

+ (NSURLSessionDownloadTask *)downloadTaskWithUID:(NSInteger)uid updateProgress:(void (^)(NSProgress *))updateProgress updateSpeed:(void (^)(id))netSpeed downloadFinished:(void (^)(id))done failure:(void (^)(NSError *))failure filePath:(void (^)(id))filePath {
    
    // get url
    NSString *url = [YXTaskManager getTaskWithUID:uid].url;
    
    // for speed test 
    __block NSDate *lastDate = [[NSDate alloc] init];
    __block unsigned long long lastSize;
    
    NSURLSessionDownloadTask *downloadTask = [YXBaseDownloadTool download:url progress:^(id progress) {
        //updateProgress(progress);
        // 获取下载速度
        if (!lastDate) {
            lastDate = [NSDate date];
            lastSize = [progress completedUnitCount];
        } else {
            NSTimeInterval t = [[NSDate date] timeIntervalSinceDate:lastDate];
            // 更新进度UI 控制刷新频率
            if (t > 0.4) {
                updateProgress(progress);
            }
                
            if (t > 1) {
                float delta = (float)([progress completedUnitCount] - lastSize);
                // KB
                if ((delta >= 1024) && (delta < 1024 * 1024)) {
                    delta = delta / 1024.f;
                    float speed = (float)delta / t;
                    netSpeed([NSString stringWithFormat:@"%.0f KB/s", speed]);
                }
                // MB
                else if ((delta >= 1024 * 1024) && (delta < 1024 * 1024 * 1024)) {
                    delta = delta / (1024.f * 1024.f);
                    float speed = (float)delta / t;
                    netSpeed([NSString stringWithFormat:@"%.1f MB/s", speed]);
                }
                lastSize = [progress completedUnitCount];
                lastDate = [NSDate date];
            }
        }
            
        // 下载完成Done
        if ([progress fractionCompleted] == 1.0) {
            done(@"successful downloaded");
        }
            
    } failure:^(NSError * error) {
        failure(error);
    } filePath:^(id path) {
        filePath(path);
    }];
        
    [downloadTask resume];
    
    return downloadTask;
}

@end
